<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="form.descrip"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-tabs v-model="contentActiveName" type="card" @tab-click="handleClick">
          <el-tab-pane label="富文本" name="first">
            <quill-editor ref="myTextEditor" v-model="form.context"></quill-editor>
          </el-tab-pane>
          <el-tab-pane label="excel导入" name="second">
            <div class="excelContent">
              <el-upload class="upload-demo" drag :action="uploadFileUrl" :limit="1" :before-upload="handleExcelBeforeUpload" :on-success="handleUploadSuccess" :on-remove="handleRemove" :headers="headers" :file-list="fileExcelList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过10M</div>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane label="word导入" name="third">
            <div class="wordContent">
              <el-upload class="upload-demo" drag :action="uploadFileUrl" :limit="1" :before-upload="handleWordBeforeUpload" :on-success="handleUploadSuccess" :on-remove="handleRemove" :headers="headers" :file-list="fileWordList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传word文件，且不超过10M</div>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane label="pdf导入" name="four">
            <div class="wordContent">
              <el-upload class="upload-demo" drag :action="uploadFileUrl" :limit="1" :before-upload="handlePdfBeforeUpload" :on-success="handleUploadSuccess" :on-remove="handleRemove" :headers="headers" :file-list="filePdfList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传pdf文件，且不超过10M</div>
              </el-upload>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="标签">
        <el-select v-model="form.targetIds" multiple filterable placeholder="请选择" style="width:100%;">
          <el-option v-for="item in biaoqianOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="user.admin" label="租户">
        <el-select v-model="form.tenantIds" multiple filterable placeholder="请选择" style="width:100%;">
          <el-option v-for="item in zuhuOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否需要审核">
        <el-switch v-model="form.isAudit" active-color="#13ce66" inactive-color="#f1f1f1">
        </el-switch>
      </el-form-item>

      <el-form-item>
        <el-button v-if="this.form.id > 0" type="primary" @click="onSubmit">立即修改</el-button>
        <el-button v-else type="primary" @click="onSubmit">立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {article_page,article_delete,article_insert,article_update,article_publish,article_detail } from "@/api/article"
import {tag_queryPage,tag_delete,tag_insert,tag_update} from "@/api/tag"
import {tenant_queryPage,tenant_delete,tenant_insert,tenant_update} from "@/api/tenant"
import { getUserProfile } from "@/api/system/user";

import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';

export default {
  name: 'Index',
  components: {
    quillEditor,
  },
  data() {
    return {
      user: {},
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/minio/uploadFile", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },

      contentActiveName: 'first',

      biaoqianOptions: [],//标签列表
      zuhuOptions: [],//租户列表

      // 表单参数
      form: {
        zoneId:null,
        id:null,
        title: '',
        descrip: '',
        context: '',//文章内容
        path:'',//文件路径
        targetIds:[],//标签id
        tenantIds:[],//租户id
        isAudit:true,//是否审核
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        descrip: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
      },

      fileSize:10,
      //excel后缀
      fileExcelType: ['xls', 'xlsx'],
      fileExcelList:[],
      //excel后缀
      fileWordType: ['dox', 'docx'],
      fileWordList:[],
      //pdf后缀
      filePdfType: ['pdf'],
      filePdfList:[],
      
    }
  },
  mounted() {
    if(this.$route.query.classid){
      this.form.zoneId = this.$route.query.classid;
    }
    console.log(this.form.zoneId);
    
    let id = this.$route.query.id;
    console.log(id);
    if(id > 0){
      this.form.id = id;
      this.getDetail();
    }

    getUserProfile().then(response => {
      this.user = response.data;
    });

    //获取标签列表
    this.getTagList();
    //获取租户列表
    this.getTenantList();
  },
  methods: {
    //获取标签列表
    getTagList() {
      tag_queryPage({pageNum:-1}).then(res => {
        this.biaoqianOptions = res.data.records;
      })
    },
    //获取租户列表
    getTenantList() {
      tenant_queryPage({pageNum:-1}).then(res => {
        this.zuhuOptions = res.data.records;
      })
    },
    //获取文章详情
    getDetail() {
      article_detail(this.form).then(res => {
        this.form = res.data;
        var suffix = this.form.path.substring(this.form.path.lastIndexOf(".") + 1);//txt
        let fileName = '';
        if(this.form.path){
          let path = this.form.path;
          path = path.split('/');
          fileName = path[path.length-1];
        }

        if(this.fileExcelType.indexOf(suffix) != -1){
          this.contentActiveName = 'second';

          if(fileName){
            this.fileExcelList = [{name:fileName,url:this.form.path}];
          }
        }else if(this.fileWordType.indexOf(suffix) != -1){
          this.contentActiveName = 'third';

          if(fileName){
            this.fileWordList = [{name:fileName,url:this.form.path}];
          }
        }else if(this.filePdfType.indexOf(suffix) != -1){
          this.contentActiveName = 'four';

          if(fileName){
            this.filePdfList = [{name:fileName,url:this.form.path}];
          }
        }
      })
    },
    onSubmit() {
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            article_update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$router.push({
                path: "/knowledge/history",
                query: { id: '' },
              });
            });
          } else {
            if(!this.user.admin){
              //非admin，填写登录用户
              this.form.tenantIds = [this.user.tenantId];
            }
            article_insert(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$router.push({
                path: "/knowledge/history",
                query: { id: '' },
              });
            });
          }
        }
      });
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 上传前校检格式和大小
    handleExcelBeforeUpload(file) {
      // 校检文件类型
      if (this.fileExcelType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileExcelType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileExcelType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleWordBeforeUpload(file) {
      // 校检文件类型
      if (this.fileWordType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileWordType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileWordType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handlePdfBeforeUpload(file) {
      // 校检文件类型
      if (this.filePdfType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.filePdfType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.filePdfType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      console.log(res);
      this.form.path = res.data;
      // this.uploadList.push({ name: res.data.url, url: res.data.url });
      // if (this.uploadList.length === this.number) {
      //   this.fileList = this.fileList.concat(this.uploadList);
      //   this.uploadList = [];
      //   this.number = 0;
      //   this.$emit("input", this.listToString(this.fileList));
      //   this.$modal.closeLoading();
      // }
    },
    // 删除文件
    handleRemove(index) {
      this.form.path = null;
    },
  }
}
</script>

<style lang="scss" scoped>
.item {
  font-size: 16px;

  .title {
    font-weight: bold;
  }

  .jianjie {
    color: #555666;
    margin-top: 8px;
  }

  .desc {
    margin-top: 8px;
    display: flex;
    align-items: center;
  }
}

::v-deep .ql-editor {
  min-height: 300px;
}

.excelContent,
.wordContent {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
